<?php

namespace app\controllers\admin\uni\order;

use app\award\Award;
use app\commission\C2;
use app\commission\PaidFinish;
use app\commission\ReceivedCommission;
use app\models\order\Order;
use app\models\order\Order as Model;
use app\models\order\OrderItem;
use app\models\order\OrderOffline;
use app\models\product\Product;
use app\models\system\SetBasic;
use app\models\system\SetExpressCompany;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserRefund;
use app\services\Chain;

/**
 * Class ProductController
 * @package app\controllers\admin
 */
class OrderController extends BaseController
{
    // 重新计算佣金
    public function actionResetCommission()
    {
        $id = $this->post('id');

        $transaction = \Yii::$app->db->beginTransaction();

        try {
            $commission = UserCommission::find()
                ->where(['order_id' => $id])
                ->all();

            if (!empty($commission)) {
                foreach ($commission as $c) {

                    $a = UserAccount::findOne(['user_id' => $c->user_id]);

                    if ($a) {
                        if ($c->status == 0) {
                            // $c->balance = 0;
                            // $c->save();
                            $a->await_balance -= $c->balance;
                            $a->save();
                        } else if ($c->status == 1) {
                            $a->balance -= $c->balance;
                            $a->save();
                        }

                        // 积分
                        $a->score -= $c->score;
                    }

                    $c->delete();
                }

            }

            $order = Order::findOne(['id' => $id]);

            // 记录重算日志
            $order->reset_log = json_encode(Chain::getReferrerChain($order->user_id));
            $order->save();

            // new Award($order);

            // 分红也要重算
            new Award($order, true, true);

            // 如果时间到了, 把待返处理成已返
            // $set = SetBasic::getLastOne();
            //
            // $time = time();
            // $expired = 3600 * 24 * $set->order_received_timeout;
            // $t = $order->create_time;
            // $t = strtotime($t);
            // if ($time - $t >= $expired) {
            //     if (ReceivedCommission::done($order->id)) {
            //
            //     }
            // }

            $transaction->commit();

            return $this->success();

        } catch (\Exception $e) {
            $transaction->rollBack();
            var_dump($e->getFile());
            var_dump($e->getLine());
            var_dump($e->getMessage());
        }
    }

    public function actionList()
    {
        $sn = $this->post('sn');
        $id = $this->post('id');

        $status = $this->post('status');
        $product = $this->post('product');

        $export = $this->post('export');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        // user
        $user_id = $this->post('user_id');
        $mobile = $this->post('mobile');

        // date
        $start = $this->post('start');
        $end = $this->post('end');

        $type = $this->post('type', -1);

        $query = Model::find()
            ->where(['!=', 'status', Model::$statusMapping['DELETE']]);
            // no group
            // ->andWhere(['is_group' => 0]);

        if ($type > -1) {
            $query->andWhere(['is_group' => $type]);
        }

        // product
        if ($product) {
            $product_ids = Product::find()
                ->where(['like', 'title', $product])
                ->select(['id'])
                ->column();
            // if ($product_ids) {
            //     $order_ids = OrderItem::find()
            //         ->where(['product_id' => $product_ids])
            //         ->select(['order_id'])
            //         ->column();
            //     if ($order_ids) {
            //         $query->andWhere(['id' => $order_ids]);
            //     }
            // }
            $order_ids = OrderItem::find()
                ->where(['product_id' => $product_ids])
                ->select(['order_id'])
                ->column();
            // var_dump($product_ids, $order_ids);exit;

            $query->andWhere(['id' => $order_ids]);
        }

        if ($start) {
            $query->andWhere(['>=', 'create_time', $start]);
        }
        if ($end) {
            $query->andWhere(['<=', 'create_time', $end]);
        }

        if ($user_id) {
            $query->andWhere(['user_id' => $user_id]);
        }

        if ($mobile) {
            $ids = User::find()
                ->where(['like', 'mobile', $mobile])
                ->select(['id'])
                ->asArray()
                ->column();
            $query->andWhere(['user_id' => $ids]);
        }

        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['id' => SORT_DESC]);
        }

        if ($id) {
            $query->andWhere(['id' => $id]);
        }
        if ($sn) {
            $query->andWhere(['like', 'sn', $sn]);
        }
        // if ($type > -1) {
        //     $query->andWhere(['is_group' => $type]);
        // }

        $with = [
            'item', 'item.product',
            'address', 'address.city',
            'user',
            'commission'
        ];

        // export
        if ($export) {
            $list = $query->with($with)->asArray()->all();
            foreach ($list as &$item) {
                $item['user']['nickname'] = base64_decode($item['user']['nickname']);
                $item['address']['nickname'] = base64_decode($item['address']['nickname']);
            }
            return $this->success(
                $list
            );
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->with($with)
            ->asArray()
            ->all();

        // 打款凭证
        foreach ($list as &$item) {
            if ($item['pay_type'] == -88) {
                $images = OrderOffline::find()
                    ->where(['order_id' => $item['id']])
                    ->with(['image'])
                    ->asArray()
                    ->all();
                $i = [];
                foreach ($images as $image) {
                    if ($image['image']['path']) {
                        array_push($i, $image['image']['path']);
                    }
                }
                $item['offline'] = $i;
            }
        }

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    public function actionView()
    {
        $id = $this->post('id');

        // order
        $model = Model::find()
            ->where(['id' => $id])
            ->with([
                'item', 'item.product', 'item.product.mainImage',
                'item.logistics', 'item.logistics.company', 'item.logistics.address', 'item.logistics.address.city',
                'address', 'address.city',
                'user',
                'commission.user','commission.user.level0'
            ])
            ->asArray()
            ->one();

        $model['user']['nickname'] = base64_decode($model['user']['nickname']);
        $model['address']['nickname'] = base64_decode($model['address']['nickname']);

        // logistics
        $logistics = SetExpressCompany::find()
            ->orderBy(['id' => SORT_ASC])
            ->asArray()
            ->all();

        // 日志
        if ($model['log']) {
            $model['log'] = json_decode($model['log']);
        }
        if ($model['reset_log']) {
            $model['reset_log'] = json_decode($model['reset_log']);
        }

        if ($model) {
            return $this->success([
                'order' => $model,
                'logistics' => $logistics
            ]);
        }

        return $this->fail('不存在该订单');
    }

    public function actionStatusList()
    {
        return $this->success(Model::statusList());
    }

    // offline
    public function actionOfflineOk()
    {
        $id = $this->post('id');

        $model = Model::findOne(['id' => $id]);
        if (!$model) {
            return $this->fail('不存在该订单');
        }
        if ($model->offline_ok == 1) {
            return $this->fail('请勿重复操作');
        }

        $model->offline_ok = 1;
        $model->save();

        PaidFinish::order($model);

        return $this->success();
    }

    // refund
    public function actionRefund()
    {

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $id = $this->post('id');
            $model = Model::findOne(['id' => $id]);
            if ($model) {
                $commission = UserCommission::find()
                    ->where(['order_id' => $model->id])
                    ->all();

                // 退余额
                if ($model->status == 1 || $model->status == 2 || $model->status == 3) {
                    $total_pay = $model->use_balance + $model->use_money;
                } else if ($model->status == 0) {
                    $total_pay = $model->use_balance;
                } else {
                    $total_pay = 0;
                }
                $account = UserAccount::findOne(['user_id' => $model->user_id]);
                $account->balance += $total_pay;
                $account->save();

                // 退佣金
                $commission_ids = [];
                foreach ($commission as $c) {
                    $a = UserAccount::findOne(['user_id' => $c->user_id]);

                    if ($c->status == 0) {
                        // $c->balance = 0;
                        // $c->save();
                        $a->await_balance -= $c->balance;
                        $a->save();
                    } else if ($c->status == 1) {
                        $a->balance -= $c->balance;
                        $a->save();
                    }
                    $c->status = -1;
                    $c->save();
                    array_push($commission_ids, $c->id);
                }

                // 订单状态
                $model->status = Order::$statusMapping['REFUND'];
                $model->save();

                // 退款记录
                $refund = new UserRefund();
                $refund->order_id = $model->id;
                $refund->commission_ids = json_encode($commission_ids);
                $refund->save();
            }

            $transaction->commit();
            return  $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }
}